<script setup lang='ts'>
import { uploadAPI } from '@/apis/common';
import { createEnterpriseAPI, getEnterpriseDetailAPI, getIndustryListAPI, updateEnterpriseAPI } from '@/apis/enterprise';
import router from '@/router';
import type { EmptyObject, Industry } from '@/types/enterprise';
import { ElMessage, type FormInstance, type FormRules, type UploadRawFile, type UploadRequestOptions, type UploadUserFile } from 'element-plus';
import { onMounted, ref } from 'vue';
import { useRoute } from 'vue-router';

// import
const addForm = ref<EmptyObject>({
  name: '', // 企业名称
  legalPerson: '', // 法人
  registeredAddress: '', // 注册地址
  industryCode: undefined, // 所在行业
  contact: '', // 企业联系人
  contactNumber: '', // 联系人电话
  businessLicenseUrl: '', // 营业执照url
  businessLicenseId: 0, // 营业执照id
}) 
//表单rules
const ruleForm = ref<FormRules<EmptyObject>>({
  name: [
    { required: true, message: '请输入企业名称', trigger: 'blur' },
  ],
  legalPerson: [
    { required: true, message: '请输入法人', trigger: 'blur' },
  ],
  registeredAddress: [
    { required: true, message: '请输入注册地址', trigger: 'blur' },
  ],
  industryCode: [
    { required: true, message: '请选择行业', trigger: 'blur' },
  ],
  contact: [
    { required: true, message: '请输入企业联系人', trigger: 'blur' },
  ],
  contactNumber: [
    { required: true, message: '请输入联系电话', trigger: 'blur' },
    { pattern: /^1[3-9]\d{9}$/, message: '请输入正确的手机号码', trigger: 'blur' }
  ],
  businessLicenseUrl: [
    { required: true, message: '请上传营业执照', trigger: 'blur' },
  ],
})

//可选择的列表
const industryList =ref<Industry[]>([])
const getIndustryList=async() => {
  const res=await getIndustryListAPI()
  // console.log(res);
  industryList.value=res.data
}
//上传图片列表
const uploadFileList=ref<UploadUserFile[]>([])
//表单实例
const formRef=ref<FormInstance>()
const submitLoading=ref(false)
const onSubmit=async() => {
  try{
    await formRef.value?.validate()
    submitLoading.value=true
    if(route.params.id ){
      //有id是编辑企业
      await updateEnterpriseAPI({
        ...addForm.value,
        id:Number(route.params.id) 
      })
      ElMessage.success('编辑企业成功')
    }else{
      await createEnterpriseAPI(addForm.value)
    ElMessage.success('添加企业成功')
    }
    
    router.back()
  }catch(error){
    console.log('err',error);
    submitLoading.value=false
  }
}

//重置表单
const onReset=() => {
formRef.value?.resetFields()
}
//上传图片
const onUploadRequest =async (options:UploadRequestOptions) => {
  console.log('options',options);
  //1,准备ForData对象
  const fd =new FormData()
  //2,加入字段
  fd.append('file',options.file)
  fd.append('type','businessLicense')
  //3,调用接口上传文件
  const res = await uploadAPI(fd)
  console.log('res',res.data.url);
  //4,返回addform,触发校验
  addForm.value.businessLicenseUrl=res.data.url
  addForm.value.businessLicenseId=res.data.id
  formRef.value?.validateField('businessLicenseUrl')
  return res.data.url
}
//删除图片
const removeupload=() => {
  //清除校验的营业执照url和id
  addForm.value.businessLicenseUrl = ''
  addForm.value.businessLicenseId = undefined
  //触发一下校验提醒一下用户
  formRef.value?.validateField('businessLicenseUrl')
}
// 在 before-upload 钩子中限制用户上传文件的格式和大小
const beforeUpload =(rawFile: UploadRawFile)=>{
  //如果大于2M就不允许上传,如果格式不是png或jpg就提示用户格式不对
  if(rawFile.size > 1024 * 1024 * 2){
    ElMessage.error('上传文件不能大于2M')
    return false
  }else if(rawFile.type !== 'image/png' && rawFile.type !== 'image/jpeg'){
    ElMessage.error('上传文件格式不正确')
    return false
  }else{
    return true
  }
}
getIndustryList()

const route = useRoute()


onMounted(() => {
  if (route.params.id) {
    getDetailData()
  }
})
const getDetailData=async()=>{
  const res = await getEnterpriseDetailAPI(route.params.id as string)
  // console.log('aaaa',res);
  const { name, legalPerson, registeredAddress, industryCode, contact, contactNumber, businessLicenseUrl }=res.data
  addForm.value = {
    name,
    legalPerson,
    registeredAddress,
    industryCode,
    contact,
    contactNumber,
    businessLicenseUrl
  }
  uploadFileList.value=[{
    name: '',
    url: businessLicenseUrl,
  }]
}
</script>

<template>
  <div class="add-enterprise">
    <header class="add-header">
      <el-page-header content="添加企业" @back="$router.back()" />
    </header>
    <main class="add-main">
      <div class="form-container">
        <div class="title">企业信息</div>
        <div class="form">
          <el-form ref="formRef" label-width="100px" :rules="ruleForm" :model="addForm">
            <el-form-item label="企业名称" prop="name">
              <el-input v-model="addForm.name" />
            </el-form-item>
            <el-form-item label="法人" prop="legalPerson" >
              <el-input v-model="addForm.legalPerson" />
            </el-form-item>
            <el-form-item label="注册地址" prop="registeredAddress">
              <el-input v-model="addForm.registeredAddress" />
            </el-form-item>
            <el-form-item label="所在行业" prop="industryCode">
              <el-select v-model="addForm.industryCode" clearable >
                <el-option v-for="item in industryList" 
                :key="item.industryCode" 
                :label="item.industryName" 
                :value="item.industryCode"
                 >
                </el-option>
              </el-select>
            </el-form-item>
            <el-form-item label="企业联系人" prop="contact">
              <el-input v-model="addForm.contact" />
            </el-form-item>
            <el-form-item label="联系电话" prop="contactNumber">
              <el-input v-model="addForm.contactNumber" />
            </el-form-item>
            <el-form-item label="营业执照" prop="businessLicenseUrl">
              
              <el-upload 
              :http-request="onUploadRequest"
              list-type="picture"
              :limit="1" 
              v-model:file-list="uploadFileList"
              :before-upload="beforeUpload"
              accept="image/jpeg,image/png"
              @remove="removeupload"
              >
              <el-button v-if="uploadFileList.length === 0" type="primary" >上传文件</el-button>
              <el-button v-else type="success"  disabled>已上传</el-button>
              </el-upload>
            </el-form-item>
          </el-form>
        </div>
      </div>
    </main>
    <footer class="add-footer">
      <div class="btn-container">
        <el-button @click="onReset">重置</el-button>
        <el-button type="primary" @click="onSubmit" :loading="submitLoading">确定</el-button>
      </div>
    </footer>
    {{ addForm }}
  </div>
</template>

<style scoped lang="scss">
.add-enterprise {
  background-color: #f4f6f8;
  height: 100vh;

  .add-header {
    display: flex;
    justify-content: space-between;
    align-items: center;
    padding: 0 20px;
    height: 64px;
    line-height: 64px;
    font-size: 16px;
    font-weight: bold;
    background-color: #fff;

    .left {
      span {
        margin-right: 4px;
      }

      .arrow {
        cursor: pointer;
      }
    }

    .right {
      text-align: right;
    }
  }

  .add-main {
    background: #f4f6f8;
    padding: 20px 130px;

    .form-container {
      background-color: #fff;

      .title {
        height: 60px;
        line-height: 60px;
        padding-left: 20px;
      }

      .form {
        margin-bottom: 20px;
        padding: 20px 65px 24px;

        .el-form {
          display: flex;
          flex-wrap: wrap;

          .el-form-item {
            width: 50%;
          }
        }
      }
    }
  }

  .add-footer {
    position: fixed;
    bottom: 0;
    width: 100%;
    padding: 24px 50px;
    color: #000000d9;
    font-size: 14px;
    background: #fff;
    text-align: center;
  }
}
</style>